<template>
  <div class="department-container">
    <div class="app-container">
      <el-card style="margin-top: 10px;">
        <!-- 具体页面结构 -->
        <page-tool>
          <!-- 插入到left插槽位置 -->
          <template #left>
            <span>本月: 社保在缴 公积金在缴</span>
          </template>
          <!-- 插入到right插槽位置 -->
          <template #right>
            <!-- 使用自定义指令 -->
            <el-button v-allow="'import_Excel'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
            <el-button v-allow="'export_Excel'" type="danger" size="small" @click="hExport">导出excel</el-button>
            <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
          </template>
        </page-tool>
        <!-- 表格 -->
        <el-table border :data="employee" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto"> -->
              <ImgHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${scope.row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDelEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="
            total,
            sizes,
            prev,
            pager,
            next,
            jumper"
            :page-sizes="[2, 5, 8, 10]"
            :page-size="pageParams.size"
            :total="total"
            :current-page.sync="currentPage"
            @current-change="hcurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 员工添加 -->
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <Emdialog
        ref="reset"
        @close="hclose"
        @update-employee="hUpdateEmployee"
      />
    </el-dialog>
    <!-- 角色分配 -->
    <el-dialog
      title="分配角色"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hCloseRole"
    >
      <AssignRole
        ref="load"
        :curid="curId"
        @Cancel="showDialogRole=false"
      />
    </el-dialog>
  </div>
</template>
<script>
import AssignRole from './assignRole.vue'
import Emdialog from './emDialog.vue'
import Type from '@/constant/employees'
const hireType = Type.hireType
const hireTypeEmploy = hireType.reduce((acc, item) => ({ ...acc, [item.id]: item.value }), {})
import { getEmployeeList, delEmployee } from '@/api/employes'
export default {
  name: 'Employee',
  components: {
    Emdialog,
    AssignRole
  },
  data() {
    return {
      employee: [],
      pageParams: { page: 1, size: 5 }, // 默认获取1页每页10条数据
      total: null, // 获取到数据的总数
      currentPage: 1,
      showDialog: false,
      showDialogRole: false, // 是否显示分配角色弹层
      curId: '' // 当前操作的员工id
    }
  },
  computed: {
    isLastPageFulled() {
      return this.total % this.pageParams.size === 0
    },
    isLastPage() {
      const maxNum = Math.ceil(this.total / this.pageParams.size)
      return this.pageParams.page === maxNum
    },
    maxNum() {
      return Math.ceil(this.total / this.pageParams.size)
    }
  },
  created() {
    // 调用获取员工列表方法
    this.loadEmployee()
  },
  methods: {
    hAdd() {
      this.showDialog = true
    },
    // 封装获取员工列表方法
    async loadEmployee() {
      try {
        const { data } = await getEmployeeList(this.pageParams)
        this.total = data.total
        this.employee = data.rows
        this.currentPage = this.pageParams.page
      } catch (err) {
        console.log(err)
      }
    },
    hcurrentChange(page) {
      // 将当前页码存入变量
      this.pageParams.page = page
      // 重新发送请求获取员工数据
      this.loadEmployee()
    },
    hSizeChange(size) {
      // 更新每页的条数
      this.pageParams.page = size
      // 重新发送请求获取员工数据
      this.loadEmployee()
    },
    // 格式化
    formatEmployment(num) {
      // 使用引入的聘用形式(通过id找到对应的value)
      // find API 执行效率比较低需要优化
      // const item = hireType.find(item => item.id === num)
      return hireTypeEmploy[num]
      // if (item === num) {
      //   return item.value
      // } else {
      //   return '不确定'
      // }
    },
    // 删除员工
    hDelEmployee(id) {
      // 提示确定要删除吗？
      this.$confirm('确认要删除吗？', '系统提示', {
        // 更改弹窗按钮提示
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 调用删除部门方法
        this.doDel(id)
      }).catch(() => {})
    },
    // 做删除
    async doDel(id) {
      await delEmployee(id)
      this.$message.success('删除成功！')
      // 如果当前表格中只有一条，删除之后自动请求上一页数据
      if (this.employee.length === 1) {
        this.pageParams.page--
        if (this.pageParams.page <= 0) {
          this.pageParams.page = 1
        }
      }
      // 重新发送请求获取员工数据
      this.loadEmployee()
    },
    // 关闭回调
    hclose() {
      this.showDialog = false
    },
    hCloseRole() {
      this.showDialogRole = false
    },
    // 子组件传递过来的回调
    hUpdateEmployee() {
      // 关闭弹层，更新表格数据
      this.showDialog = false
      if (this.isLastPageFulled) {
        this.pageParams.page = this.maxNum + 1
      } else {
        this.pageParams.page = this.maxNum
      }
      this.loadEmployee()
    },
    // 弹层关闭的回调
    hClose() {
      this.$refs.reset.resetFrom()
    },
    // excel导出
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getEmployeeList(this.pageParams)
        const list = res.data.rows
        const { header, data } = this.formData(list)
        // 导出下载文件实现
        excel.export_json_to_excel({
          header,
          data
        })
      })
    },
    // excel导出格式优化
    formData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      let data = []
      const one = list[0]
      if (!one) return { header, data }
      header = Object.keys(one).map(key => {
        return map[key]
      })
      data = list.map(obj => {
        // 把obj转换为
        const key = obj['formOfEmployment']
        obj['formOfEmployment'] = hireTypeEmploy[key]
        return Object.values(obj)
      })
      return { header, data }
    },
    // 点击了角色分配
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
      // 每次打开都要获取员工的角色信息
      this.$nextTick(() => {
        this.$refs.load.loadUserDetailById()
      })
    }
  }
}
</script>
